//
//  GGSort.m
//  GGFriendTable
//
//  Created by lisheng on 16/3/13.
//  Copyright © 2016年 鬼谷传人. All rights reserved.
//

#import "GGSort.h"

@implementation GGSort
+ (void)sortArray:(NSArray *)dataSourceArray completionHandle:(void (^)(NSArray *, NSDictionary *))keysBlock
{
    
    NSMutableDictionary *dataSourceDictionary = [[NSMutableDictionary alloc] initWithCapacity:0];
    
    //将dataSourceArray 转换成 key为A,B,C...类的字典,
    for (NSString * value in dataSourceArray) {
        
        NSString * key = [self getFirstCharByString:value];
        if ([[dataSourceDictionary allKeys] containsObject:key]) {
            [dataSourceDictionary[key] addObject:value];
        }else {
            NSMutableArray * valuesArray = [NSMutableArray array];
            [valuesArray addObject:value];
            [dataSourceDictionary setObject:valuesArray forKey:key];
            
        }
    }
    NSArray * keysArray = [self getKeysInOrderByDictionary:dataSourceDictionary];
    
    keysBlock(keysArray,dataSourceDictionary);
    
}


#pragma mark - 汉字转拼音,获得首字母大写
+ (NSString *)getFirstCharByString:(NSString *)str {
    
    NSString * firstChar = [[self getPinYinByString:str] substringToIndex:1];
    NSString * upFirstChar = [firstChar uppercaseString]; //这里是首字母 大写
    
    return upFirstChar;
}
+ (NSString *)getPinYinByString:(NSString *)str {
    
    NSString * firstString = [str substringToIndex:1];
    CFStringRef strRef = (__bridge CFStringRef)firstString;
    CFMutableStringRef muStrRef = CFStringCreateMutableCopy(NULL, 0, strRef);
    CFStringTransform(muStrRef, NULL, kCFStringTransformMandarinLatin, NO);
    NSString * newStr = (__bridge NSString *)muStrRef; // 这里是完整拼音
    
    return newStr;
}
#pragma mark - make dictionary keys and values in order ,(e.g. "ABCD...Z")
+ (NSArray *)getKeysInOrderByDictionary:(NSDictionary *)dic {
    NSArray * keysArray = [dic allKeys];
    return [self sortedArray:keysArray];
}
#pragma mark - 数组中的字符串排序
+ (NSArray *)sortedArray:(NSArray *)array {
    array = [array sortedArrayUsingComparator:^NSComparisonResult(NSString * obj1, NSString * obj2) {
        return [obj1 compare:obj2 options:NSCaseInsensitiveSearch];
    }];
    return array;
}
@end
